package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.PageParam;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Employees;
import com.itheima.reggie.service.EmployeesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/employee")
public class EmployeesController {
    @Autowired
    private EmployeesService employeesService;

    /**
     * 添加员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R add(@RequestBody Employees employee) {

        String password = DigestUtils.md5DigestAsHex("123456".getBytes());

        employee.setPassword(password);


        if (employeesService.save(employee)) {

            return R.success("添加成功!");
        }
        return R.error("添加失败!");

    }

    /**
     * 员工分页查询
     *
     * @param p
     * @return
     */
    @GetMapping("/page")
    public R page(PageParam p) {

        LambdaQueryWrapper<Employees> lqw = new LambdaQueryWrapper<>();

        lqw.like(p.getName() != null, Employees::getName, p.getName());

        IPage<Employees> page = new Page<>(p.getPage(), p.getPageSize());
        employeesService.page(page, lqw);

        return R.success(page);
    }

    @PutMapping
    public R update(@RequestBody Employees employee) {

        if (employeesService.updateById(employee)) {

            return R.success("更新成功!");
        }
        return R.error("更新失败!");

    }

    @GetMapping("/{id}")
    public R findById(@PathVariable Long id) {
        Employees e = employeesService.getById(id);

        return R.success(e);

    }
}
